import * as fs from 'fs'
import * as path from 'path'
import * as xlsx from 'xlsx'

// interface MergedColumn {
//   from: number
//   to: number
//   firstRowValue: string
// }
const fileNameIndex = 1

// type MergedColumns = Record<string, MergedColumn>

// interface AliasPosition {
//   rowIndex: number
//   columnIndex: number
// }
// '别名的位置'
function findAliasPosition(matrix) {
	const targetAlias = '别名'
	for (let i = 0; i < matrix.length; i++) {
		const row = matrix[i]
		const columnIndex = row.indexOf(targetAlias)
		if (columnIndex !== -1) {
			return { rowIndex: i, columnIndex }
		}
	}
	console.log('列名 "别名" 不存在！')
	process.exit(1)
}

// 一个导出的转换函数
function toSingleQuotedValues(obj) {
	const entries = Object.entries(obj).map(([key, value]) => {
		if (typeof value === 'string') {
			return `  ${key}: ${value.includes("'") ? `"${value}"` : `'${value}'`}`
		}
		return `  ${key}: ${value}`
	})
	return entries.join(',\n')
}

function ensureDirectoryExists(directoryPath) {
	try {
		fs.mkdirSync(directoryPath, { recursive: true })
	} catch (error) {
		console.error(`创建目录失败: ${directoryPath}`, error)
		process.exit(1)
	}
}

// console.log('mergeCell.s.c',mergeCell.s.c)
// console.log('mergeCell.e.c',mergeCell.e.c)
function getMergedColumns(worksheet) {
	const mergedColumns = {}
	;(worksheet['!merges'] || []).forEach((mergeCell) => {
		for (let col = mergeCell.s.c; col <= mergeCell.e.c; col++) {
			const column = xlsx.utils.encode_col(col)
			const firstRowValue = worksheet[xlsx.utils.encode_cell({ r: fileNameIndex, c: col })]?.v
			if (!mergedColumns[column]) {
				const fromIndex = col
				const toIndex = mergeCell.e.c
				mergedColumns[column] = {
					from: fromIndex,
					to: toIndex,
					firstRowValue: firstRowValue
				}
			}
		}
	})
	return mergedColumns
}

function getMergeData(mergedColumns) {
	const mergeData = {}
	// const mergeData: Record<string, MergedColumn> = {}
	for (const column in mergedColumns) {
		const { from, to, firstRowValue } = mergedColumns[column]
		if (firstRowValue !== undefined) {
			if (!mergeData[firstRowValue]) {
				mergeData[firstRowValue] = {
					from: from,
					to: to,
					firstRowValue: firstRowValue
				}
			} else {
				mergeData[firstRowValue].to = to
			}
		}
	}
	return mergeData
}

function getCategorizedData(mergeData, cleanedExcelData, aliasKey, aliasRowIndex) {
	const categorizedData = {}

	for (const key in mergeData) {
		if (Object.prototype.hasOwnProperty.call(mergeData, key)) {
			const { from, to } = mergeData[key]
			const categoryData = cleanedExcelData.slice(fileNameIndex).map((row) => row.slice(from, to + fileNameIndex))
			categorizedData[key] = aliasKey.reduce((obj, alias, index) => {
				const rgbaValueIndex = categoryData[1].indexOf('RGBA')
				if (rgbaValueIndex !== -1) {
					obj[alias] = categoryData.slice(aliasRowIndex).map((cell) => cell[rgbaValueIndex])[index]
				}
				return obj
			}, {})
		}
	}

	return categorizedData
}

function generateEnumContent(categorizedData) {
	return Object.keys(categorizedData)
		.map((key, index) => `  '${key}' = '${key}',`)
		.join('\n')
}

function saveToFile(filePath, content) {
	fs.writeFileSync(filePath, content)
}

// 外部调用入口函数
export default function xlsxTransformTheme() {
	const rootDirectory = process.cwd()
	const sheetName = 'Sheet1'

	const workbook = xlsx.read(fs.readFileSync(path.join(rootDirectory, '/tools/theme/theme.xlsx')), {
		type: 'array'
	})

	const worksheet = workbook.Sheets[sheetName]

	const excelData = xlsx.utils.sheet_to_json(worksheet, {
		defval: '', // 默认值为空字符串
		header: 1 // 指定第一行为标题
	})

	// console.log('%c [  ]-137', 'font-size:13px; background:pink; color:#bf2c9f;', excelData)
	const cleanedExcelData = excelData.filter((row) => row.some((cell) => cell !== ''))
	// console.log('cleanedExcelData',cleanedExcelData);
	const aliasPosition = findAliasPosition(cleanedExcelData)

	const aliasColumnIndex = aliasPosition.columnIndex
	const aliasRowIndex = aliasPosition.rowIndex
	// console.log('aliasColumnIndex',aliasColumnIndex)
	// console.log('aliasRowIndex',aliasRowIndex)
	// 【0，2】

	// console.log('%c [  ]-149', 'font-size:13px; background:pink; color:#bf2c9f;', worksheet)
	const mergedColumns = getMergedColumns(worksheet)
	console.log('mergedColumns', mergedColumns)

	const mergeData = getMergeData(mergedColumns)
	console.log('mergeData', mergeData)

	// 数据key 添加-- 以及将_转为-
	const aliasKey = cleanedExcelData
		.slice(aliasRowIndex + 1)
		.map((row) => `'--${row[aliasColumnIndex].replace(/_/g, '-').trim()}'`)
	// console.log('aliasKey',aliasKey)
	const categorizedData = getCategorizedData(mergeData, cleanedExcelData, aliasKey, aliasRowIndex)
	console.log('categorizedData', categorizedData)
	const enumContent = generateEnumContent(categorizedData)

	const outputDirectory = path.join(rootDirectory, 'src/generated/theme')
	ensureDirectoryExists(outputDirectory)

	const enumFilePath = path.join(rootDirectory, 'src/generated/theme/theme-enum.ts')
	saveToFile(enumFilePath, `enum ThemeEnum {\n${enumContent}\n}\nexport default ThemeEnum;`)
	console.log(`成功写入文件: ${enumFilePath}`)

	for (const key in categorizedData) {
		if (Object.prototype.hasOwnProperty.call(categorizedData, key)) {
			const value = categorizedData[key]
			const processedValue = toSingleQuotedValues(value)

			const filename = path.join(outputDirectory, `${key}.ts`)
			const fileContent = `export default {\n${processedValue}\n}\n`

			saveToFile(filename, fileContent)
			console.log(`成功写入文件: ${filename}`)
		}
	}
}

xlsxTransformTheme()
